# coding:utf-8
'''
Created on 2010-1-4

@author: Jason Green
@author-email: guileen@gmail.com

Char  Dec  Oct  Hex | Char  Dec  Oct  Hex | Char  Dec  Oct  Hex | Char Dec  Oct   Hex
-------------------------------------------------------------------------------------
(nul)   0 0000 0x00 | (sp)   32 0040 0x20 | @      64 0100 0x40 | `      96 0140 0x60
(soh)   1 0001 0x01 | !      33 0041 0x21 | A      65 0101 0x41 | a      97 0141 0x61
(stx)   2 0002 0x02 | "      34 0042 0x22 | B      66 0102 0x42 | b      98 0142 0x62
(etx)   3 0003 0x03 | #      35 0043 0x23 | C      67 0103 0x43 | c      99 0143 0x63
(eot)   4 0004 0x04 | $      36 0044 0x24 | D      68 0104 0x44 | d     100 0144 0x64
(enq)   5 0005 0x05 | %      37 0045 0x25 | E      69 0105 0x45 | e     101 0145 0x65
(ack)   6 0006 0x06 | &      38 0046 0x26 | F      70 0106 0x46 | f     102 0146 0x66
(bel)   7 0007 0x07 | '      39 0047 0x27 | G      71 0107 0x47 | g     103 0147 0x67
(bs)    8 0010 0x08 | (      40 0050 0x28 | H      72 0110 0x48 | h     104 0150 0x68
(ht)    9 0011 0x09 | )      41 0051 0x29 | I      73 0111 0x49 | i     105 0151 0x69
(nl)   10 0012 0x0a | *      42 0052 0x2a | J      74 0112 0x4a | j     106 0152 0x6a
(vt)   11 0013 0x0b | +      43 0053 0x2b | K      75 0113 0x4b | k     107 0153 0x6b
(np)   12 0014 0x0c | ,      44 0054 0x2c | L      76 0114 0x4c | l     108 0154 0x6c
(cr)   13 0015 0x0d | -      45 0055 0x2d | M      77 0115 0x4d | m     109 0155 0x6d
(so)   14 0016 0x0e | .      46 0056 0x2e | N      78 0116 0x4e | n     110 0156 0x6e
(si)   15 0017 0x0f | /      47 0057 0x2f | O      79 0117 0x4f | o     111 0157 0x6f
(dle)  16 0020 0x10 | 0      48 0060 0x30 | P      80 0120 0x50 | p     112 0160 0x70
(dc1)  17 0021 0x11 | 1      49 0061 0x31 | Q      81 0121 0x51 | q     113 0161 0x71
(dc2)  18 0022 0x12 | 2      50 0062 0x32 | R      82 0122 0x52 | r     114 0162 0x72
(dc3)  19 0023 0x13 | 3      51 0063 0x33 | S      83 0123 0x53 | s     115 0163 0x73
(dc4)  20 0024 0x14 | 4      52 0064 0x34 | T      84 0124 0x54 | t     116 0164 0x74
(nak)  21 0025 0x15 | 5      53 0065 0x35 | U      85 0125 0x55 | u     117 0165 0x75
(syn)  22 0026 0x16 | 6      54 0066 0x36 | V      86 0126 0x56 | v     118 0166 0x76
(etb)  23 0027 0x17 | 7      55 0067 0x37 | W      87 0127 0x57 | w     119 0167 0x77
(can)  24 0030 0x18 | 8      56 0070 0x38 | X      88 0130 0x58 | x     120 0170 0x78
(em)   25 0031 0x19 | 9      57 0071 0x39 | Y      89 0131 0x59 | y     121 0171 0x79
(sub)  26 0032 0x1a | :      58 0072 0x3a | Z      90 0132 0x5a | z     122 0172 0x7a
(esc)  27 0033 0x1b | ;      59 0073 0x3b | [      91 0133 0x5b | {     123 0173 0x7b
(fs)   28 0034 0x1c | <      60 0074 0x3c | \      92 0134 0x5c | |     124 0174 0x7c
(gs)   29 0035 0x1d | =      61 0075 0x3d | ]      93 0135 0x5d | }     125 0175 0x7d
(rs)   30 0036 0x1e | >      62 0076 0x3e | ^      94 0136 0x5e | ~     126 0176 0x7e
(us)   31 0037 0x1f | ?      63 0077 0x3f | _      95 0137 0x5f | (del) 127 0177 0x7f

9 \t
12 \n
13 \r
32-47    (sp)!"#$%&'()*+,-./
48-57    0-9
58-64    :;<=>?@
65-90    A-Z
91-96    [\]^_`
97-122    a-z
123-126  {|}~
共计 98个字符  98= 01100010

常用的 'a-z','A-Z','0-9','.',
常用组合 [a-z],[A-Z],[a-zA-Z],[01],[0-9],[0-9A-F],[\n\r\t]
(码表,码长,码...)(码表,码长,码...)(码表,码长,码...)

码表+码长是定义码，定义码的实现方式可以改写
plan A: 码表+码长 不能超过 01100010 , 前6位表达码长，后两位表达码表，码长不能超过011000=24, 码表不能超过 010,可以是 00,01,10
plan B: 码表=高四位 0110  ，码长=低四位 1111，当码表=0110时，码长不能超过010 
plan C  码表=高3位 ，码长=低6位，如果码表是码长属性固定为1，则低6位用作编码，通常用来表达符号，符号总是单独出现，很少连续出现。
定义好码表是压缩的关键，码表里的字符数量应当是 2的幂 
[a-z,][A-Z][0-9A-F]

源  转换为码表T指定的进制的数n1（如3进制数： 01221211021）,n1转换为目标编码进制数如98进制数得出 n2,n2的98进制位数为码长L,得出结果为 T~L~n2 
'''

def any_to_decimal(input,_from):
    d=0
    for i, v in enumerate(reversed(input)):
        assert v<_from ,"toDecimal v must less than _from , v=%d,_from=%d " % (v,_from)
        d += v *(_from**i)
    return d


def decimal_to_any(input,_to):
    res = []
    x = input
    while x>0:
        res.insert(0, x % _to)
        x = x//_to
    return res
d =  any_to_decimal([1,0,1,0,1,0], 2)
b =  decimal_to_any(d, 16)

def to_64scale(num):
    if(num==0):
        return [0]
    res = []
    while num>0:
        res.insert(0, num & 0x3F)
        num = num>>6
    return res
    
def any_to_any(input,_from,_to):
    '''
    进制转换
    @param input:
    @param _from:
    @param _to:
    '''
    return decimal_to_any(any_to_decimal(input, _from), _to)     

def compress_by_table(input,table=[],dest_table=[]):
    nums=[]
    for c in input:
        nums.append(table.index(c))
    nums = any_to_any(nums, len(table), len(dest_table))
    v=''
    for n in nums:
        v += dest_table[n]
    return v
#input = '513246976595'
#v = compress_by_table(input, '0123456789', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+`-={}:"|<>?[];\'\\,./')


_crypt_table='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.'
def ascii_crypt(num):
    nums = to_64scale(num)
    v=''
    for n in nums:
        v += _crypt_table[n]
    return v
def ascii_decrypt(str):
    num = 0
    for c in str:
        num = (num<<6) | _crypt_table.index(c)
    return num

#s = ascii_crypt(16700000)
#print s
#print ascii_decrypt(s)
#print any_to_decimal([63,63,63,63], 64)

#from django.utils.cache import cache
cache={}
_key_dict={}
def compress_key(raw_key):
    key=_key_dict.get(raw_key) or cache.get('k.%s' % raw_key)
    if(not key):
        num=cache.incr('key_version')
        key = ascii_crypt(num)
        cache.set('k.%s'%raw_key,key)
        dict[input]=key
    return key
def get(key):
    return cache.get(compress_key(key))

#将dict序列化到文件系统
#使用一个服务来获取key，避免多进程，分布式问题
import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "%s wrote:" % self.client_address[0]
        print self.data
        # just send back the same data, but upper-cased
        self.request.send(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()


